<?php
namespace app\lawcase\model;

use think\Model;
use think\facade\Db;

class CaseCause extends Model
{
    // 设置当前模型对应的数据表名称
    protected $name = 'case_cause';
    // 设置数据表前缀
    protected $prefix = 'oa_';
    
    // 获取案由选择列表数据
    public function getSelectData($where = [], $param = [])
    {
        try {
            // 获取所有案由数据
            $list = $this->where($where)
                ->where('delete_time', 0)
                ->field('id, name, parent_id')
                ->order('sort asc, id asc')
                ->select()
                ->toArray();

            // 构建树形结构
            $tree = $this->buildSelectTree($list);
            return $tree;
        } catch (\Exception $e) {
            return [];
        }
    }

    // 构建下拉选择树形结构
    private function buildSelectTree($list, $parentId = 0, $level = 0)
    {
        $tree = [];
        $prefix = str_repeat('├─', $level);
        foreach ($list as $item) {
            if ($item['parent_id'] == $parentId) {
                $item['name'] = $prefix . $item['name'];
                $tree[] = [
                    'id' => $item['id'],
                    'name' => $item['name'],
                    'parent_id' => $item['parent_id']
                ];
                // 递归获取子级
                $children = $this->buildSelectTree($list, $item['id'], $level + 1);
                $tree = array_merge($tree, $children);
            }
        }

        return $tree;
    }

    // 获取列表数据
    public function getList($where = [], $rows = 10000, $param = [])
    {
        try {
            $order = ['sort' => 'asc', 'id' => 'asc'];
            $list = $this->where($where)
                        ->where('delete_time', 0)
                        ->order($order)
                        ->select()
                        ->toArray();
            return $list;
        } catch (\Exception $e) {
            return [];
        }
    }

    // 构建树形结构
    public function buildTreeFromList($list)
    {
        if (empty($list)) {
            return [];
        }

        $tree = [];
        $temp = [];

        // 以ID为索引重新组织数组
        foreach ($list as $item) {
            $temp[$item['id']] = $item;
        }// 构建树形结构
        foreach ($temp as $id => $item) {
            if (isset($temp[$item['parent_id']])) {
                $temp[$item['parent_id']]['children'][] = &$temp[$id];
            } else {
                $tree[] = &$temp[$id];
            }
        }return $tree;
    }

    // 添加案由
    public function add($param)
    {
        try {
            // 设置创建时间
            $param['create_time'] = time();
            // 初始化关联案件数为0
            $param['case_count'] = 0;
            $insertId = $this->strict(false)->insertGetId($param);
            add_log('add', $insertId, $param);
        } catch (\Exception $e) {
            return to_assign(401, '添加失败');
        }
        return to_assign(0,'操作成功',['return_id'=>$insertId]);
    }

    // 编辑案由
    public function edit($param)
    {
        try {
            $param['update_time'] = time();
            $this->strict(false)->where('id', $param['id'])->update($param);
            add_log('edit', $param['id'], $param);
        } catch (\Exception $e) {
            return to_assign(1, '修改失败');
        }
        return to_assign(0,'操作成功',['return_id'=>$param['id']]);
    }

    // 获取案由详情
    public function getDetail($id)
    {
        try {
            return $this->where('id', $id)->find();
        } catch (\Exception $e) {
            return null;
        }
    }

    // 删除案由
    public function remove($id)
    {
        $errorMsg = '';
        try {
            // 检查是否有子级
            $hasChildren = $this->where('parent_id', $id)->where('delete_time', 0)->count() > 0;
            if ($hasChildren) {
                $errorMsg = '该案由下存在子级案由，无法删除';
                return to_assign(1, $errorMsg);
            }

            // 检查是否有关联案件
            // 注意：这里需要根据实际的数据库结构来修改
            // 假设有一个 cases 表，其中有一个 case_cause_id 字段关联到案由
            $hasRelatedCases = Db::name('lawcase')->where('case_cause_id', $id)->count() > 0;
            if ($hasRelatedCases) {
                $errorMsg = '该案由已关联案件，无法删除';
                return to_assign(1, $errorMsg);
            }

            // 执行软删除
            self::where('id', $id)->update(['delete_time' => time()]);
            add_log('delete', $id);

        } catch (\Exception $e) {
            return to_assign(1, '删除失败：' . $e->getMessage());
        }
        return to_assign();
    }

    // 更新排序
    public function updateSort($data)
    {
        try {
            return $this->where('id', $data['id'])->update(['sort' => $data['sort']]);
        } catch (\Exception $e) {
            return false;
        }
    }

}